package cn.cw.gongjun.ui.dashboard;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.text.SimpleDateFormat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.cw.gongjun.R;
import cn.cw.gongjun.utils.Tools;
import cn.cw.gongjun.widget.TimeLineView;

@SuppressLint("NonConstantResourceId")
public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    private Context mContext;

    @BindView(R.id.order_no)
    EditText order_no;
    @BindView(R.id.select_btn)TextView select_btn;
    @BindView(R.id.typename)TextView  typename;
    @BindView(R.id.tlv) TimeLineView tlv;
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        ButterKnife.bind(this, root);
        mContext = getContext();
//        tlv.setHeightLineProvider(this);


        final TextView textView = root.findViewById(R.id.text_dashboard);
        dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
    public Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }
    @OnClick({R.id.select_btn})
    public void itemClick(){
        Editable text = order_no.getText();
        String number = text.toString();

        if(number.length()<=0){
            Tools.toast(getContext(),"请输入运单号");
            return;
        }
        removeView();
        OkGo.<String>get("http://jisuexpress.api.bdymkt.com/express/query")
                .headers("X-Bce-Signature","AppCode/81e14d16675446868edad16f0bed9cf5")
                .params("number",number)
                .params("type","auto")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        Log.i(TAG, "Size: " + response.body());
                        JSONObject jsonObject = JSON.parseObject(response.body());
                        Log.i("convertResponse", "response: " + jsonObject.toJSONString());

                        String msg = jsonObject.getString("msg");
                        if(msg.equals("ok")){

                            Object result = jsonObject.get("result");
                            JSONObject jsonObject1 = JSON.parseObject(result.toString());
                            typename.setText(jsonObject1.getString("typename"));
                            JSONArray list = jsonObject1.getJSONArray("list");
                            for (int i = 0; i < list.size(); i++) {
//                                list.get(i).getClass()
                                LogisticsStatus logisticsStatus = JSONObject.parseObject(list.get(i).toString(), LogisticsStatus.class);
                                addItem(logisticsStatus.getStatus(),logisticsStatus.getTime());
                            }
                        }
                    }
                });
    }

    private void addItem(String status,String time) {
        View v = LayoutInflater.from(mContext).inflate(R.layout.logistics_status_layout, tlv, false);
        ((TextView) v.findViewById(R.id.tx_action)).setText(status);
        ((TextView) v.findViewById(R.id.tx_action_time)).setText(time);
        ((TextView) v.findViewById(R.id.tx_action_status)).setText("状态");
        tlv.addView(v);
        @SuppressLint("UseCompatLoadingForDrawables") BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.round_check_fill);
        tlv.setHeightBitmap(zoomImg(bitmapDrawable.getBitmap(), 100, 100));
    }

    public void removeView() {
        if (tlv.getChildCount() != 0) {
            for (int i = 0; i < tlv.getChildCount(); i++) {
                tlv.removeViewAt(i);
            }

        }
    }
}